<template>
  <el-card>
    <template #header>
      <div class="card-header">
        <el-icon><Histogram /></el-icon>
        <span>今日日志类型分布</span>
      </div>
    </template>
    <div class="chart-container">
      <div ref="chartContainer" class="echart-container"></div>
    </div>
  </el-card>
</template>

<script setup lang="ts">
import { ref, watch, onMounted, onUnmounted } from 'vue'
import { Histogram } from '@element-plus/icons-vue'
import * as echarts from 'echarts'
import { getColorByCharCode } from '@/utils'
import useApiStore from '@/core/apiStore'

const apiStore = useApiStore()

const chartContainer = ref<HTMLElement | null>(null)
let chart: echarts.ECharts | null = null

onMounted(() => {
  if (chartContainer.value) {
    chart = echarts.init(chartContainer.value)
  }
})

onUnmounted(() => {
  if (chart) {
    chart.dispose()
  }
})

const updateChart = (data: { count: number; log_type: string }[]) => {
  if (chart && chartContainer.value) {
    const { distributions = [] } = data
    const xAxisData = distributions.map(item => item.log_type)
    const seriesData = distributions.map(item => ({
      value: item.count,
      itemStyle: { color: getColorByCharCode(item.log_type) },
    }))

    const option = {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow',
        },
      },
      xAxis: {
        type: 'category',
        data: xAxisData,
        axisLine: {
          lineStyle: {
            color: '#999',
          },
        },
        axisTick: {
          alignWithLabel: true,
        },
      },
      yAxis: {
        type: 'value',
        axisLine: {
          show: true,
          lineStyle: {
            color: '#999',
          },
        },
        splitLine: {
          lineStyle: {
            color: '#f0f0f0',
          },
        },
      },
      series: [
        {
          name: '日志数',
          type: 'bar',
          barWidth: '40%',
          data: seriesData,
          label: {
            show: true,
            position: 'top',
          },
        },
      ],
    }

    chart.setOption(option)
  }
}

watch(apiStore.apiStates.todayTypeDistribution, newVal => {
  if (newVal.data?.data) {
    updateChart(newVal.data.data)
  }
})
</script>

<style lang="scss" scoped>
.chart-container {
  position: relative;
  height: 250px;
  width: 100%;

  .echart-container {
    width: 100%;
    height: 100%;
  }
}
</style>
